﻿using System.Collections;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UIBagItemRender : MonoBehaviour,IDragHandler,IBeginDragHandler,IEndDragHandler 
{
    public Image imgIcon;

    public ItemData data;

    private static bool isDragging;
    private static ScrollRect parentScroll;
    public void SetData(ItemData v)
    {
        data = v;   
        if (data != null)
        {
            ItemInfo itemInfo = data.GetItemInfo();
            if (itemInfo.icon != "")
            {
                imgIcon.sprite = Resources.Load<Sprite>("Icon/" + itemInfo.icon);
                imgIcon.gameObject.SetActive(true);
            }
            else imgIcon.gameObject.transform.parent.gameObject.SetActive(false);
        }
        else
        {
            imgIcon.gameObject.transform.parent.gameObject.SetActive(false);
        }
    }

    public void OnBeginDrag(PointerEventData eventData)
    {
        if (Mathf.Abs(eventData.delta.x) > Mathf.Abs(eventData.delta.y))
        {
            if (data == null)
                return;

            isDragging = true;
            parentScroll = null;
        }
        else
        {
            parentScroll = GetComponentInParent<ScrollRect>();
            isDragging = false;
        }

        if (isDragging)
        {
            GameObject obj = Instantiate(gameObject, UIRoot.canvas.transform);
            UIBagItemRender equipRender = obj.GetComponent<UIBagItemRender>();
            equipRender.SetData(data);
            CanvasGroup canvasGroup = obj.AddComponent<CanvasGroup>();
            canvasGroup.blocksRaycasts = false;
            UIRoot.objDrag = obj;
        }
        else if (parentScroll != null)
        {
            parentScroll.OnBeginDrag(eventData);
        }
    }

    public void OnDrag(PointerEventData eventData)
    {
        if (isDragging)
        {
            if (UIRoot.objDrag != null)
                UIRoot.objDrag.transform.position = Input.mousePosition;
        }
        else if (parentScroll != null)
        {
            parentScroll.OnDrag(eventData);
        }
    }

    public void OnEndDrag(PointerEventData eventData)
    {
        if (isDragging)
        {
            if (UIRoot.objDrag != null)
                Destroy(UIRoot.objDrag);
            UIRoot.objDrag = null;
            isDragging = false;
        }
        else if (parentScroll != null)
        {
            parentScroll.OnEndDrag(eventData);
        }

    }
}
